package com.atguigu.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("flowLimit")
@Slf4j
public class FlowLimitController {

    @GetMapping("/testA")
    public String testA(){
        /*log.info("进入线程A");
        try {
            TimeUnit.MILLISECONDS.sleep(2000);
            log.info("返回1");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        log.info("返回2");
        return "---------------A";
    }


    @GetMapping("/testB")
    public String testB(){
        log.info(Thread.currentThread().getName()+"\t"+"...testB");
        return "---------------B";
    }


    /**
     * 测试 RT 当请求超过好多秒后，开启服务降级保护
     * @return
     */
    @GetMapping("/testD")
    public String testD(){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("testD 测试RT");
        return "---------------testD";
    }


    /**
     * testD 测试异常比例,当异常比例达到某个值会自动熔断
     * @return
     */
    @GetMapping("/testE")
    public String testE(){

        log.info("testE 测试异常比例");
        int age = 10 / 0;
        return "---------------testE";
    }

    /**
     * testD 测试异常总数, 当好多秒内异常数达到多少可启用服务熔断和降级
     * @return
     */
    @GetMapping("/testF")
    public String testF(){

        log.info("testF 测试异常比例");
        int age = 10 / 0;
        return "---------------testF";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "del_testHotKey") // 服务降级 或熔断 处理
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
                             @RequestParam(value = "p2",required = false) String p2) {
        return "testE 测试异常数";
    }

    public String del_testHotKey(String p1, String p2, BlockException exception){
        return "----del_testHotKey";
    }
}
